package com.qf.game.application.utils;

import com.qf.game.application.entity.Player;
import com.qf.game.application.entity.Room;

import javax.websocket.Session;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 房间管理工具
 *
 * roomMap-
 *   1 - Room1
 *   2 - Room2
 *   ....
 *
 * sessionMap-
 *   session1 - Room1
 *   session2 - Room1
 *
 */
public class RoomManagerUtils {

    /**
     * 基于房间号 - 管理房间 （房间号 - 房间对象）
     */
    private static Map<Integer, Room> roomMap = new ConcurrentHashMap<>();

    /**
     * 基于玩家的连接 - 管理房间 （玩家连接对象 - 房间对象）
     */
    private static Map<Session, Room> sessionRoomMap = new ConcurrentHashMap<>();

    //添加房间
    public static void putRoom(Integer rid, Room room){
        roomMap.put(rid, room);
    }

    //添加房间
    public static void putRoom(Session session, Room room){
        sessionRoomMap.put(session, room);
    }

    //根据房间号 获得房间对象
    public static Room getRoom(Integer rid) {
        return roomMap.get(rid);
    }

    //根据session连接 获得房间对象
    public static Room getRoom(Session session){
        return sessionRoomMap.get(session);
    }

    //删除房间
    public static void removeRoom(Integer roomId){
        Room removeRoom = roomMap.remove(roomId);
        //连带着 sessionMap中的房间也要移除
        if(removeRoom != null){
            Session session1 = removeRoom.getPlayer1().getSession();
            Session session2 = removeRoom.getPlayer2().getSession();

            //移除SessionMap中的房间
            sessionRoomMap.remove(session1);
            sessionRoomMap.remove(session2);
        }
    }

    //根据session移除房间
    public static void removeRoom(Session session){
        Room removeRoom = sessionRoomMap.remove(session);
        if (removeRoom != null) {
            //根据房间id移除房间
            roomMap.remove(removeRoom.getRid());
            //从房间中找到对手玩家
            Player otherPlayer = removeRoom.getOtherPlayer(session);
            if (otherPlayer != null) {
                Session otherSession = removeRoom.getOtherPlayer(session).getSession();
                sessionRoomMap.remove(otherSession);
            }
        }
    }

    /**
     * 返回所有房间列表
     * @return
     */
    public static List<Room> getRooms(){
        return new ArrayList<>(roomMap.values());
    }
}
